package com.ckh.springboot.controller;

import com.ckh.springboot.common.Result;
import com.ckh.springboot.entity.SysAnnouncement;
import com.ckh.springboot.entity.User;
import com.ckh.springboot.service.ISysAnnouncementService;
import com.ckh.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;
import com.ckh.springboot.utils.TokenUtils;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/api/announcement")
@CrossOrigin(origins = "http://localhost:9528")
public class SysAnnouncementController {

    @Resource
    private ISysAnnouncementService sysAnnouncementService;

    @Resource
    private IUserService userService;

    private User getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
            String userId = JWT.decode(token).getAudience().get(0);
            return userService.getById(Integer.valueOf(userId)); // 使用正确的 userService
        }
        String userId = request.getHeader("userId"); // 确保从请求头中获取 userId
        if (userId != null) {
            return userService.getById(Integer.valueOf(userId));
        }
        return null; // 如果无法获取 userId，返回 null
    }
  
    // 权限校验
    private boolean isAdminOrTeacher(User user) {
        return user != null && (
            Integer.valueOf(1).equals(user.getIdentity()) || // 老师
            "admin".equals(user.getStudentId())              // 超级管理员
        );
    }
    @PostMapping("/create")
    public Result create(@RequestBody SysAnnouncement announcement, @RequestParam Integer userId) {
        announcement.setCreateTime(new Date());
        announcement.setStatus(1);
        announcement.setCreateUserId(userId);
        sysAnnouncementService.save(announcement);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody SysAnnouncement announcement, HttpServletRequest request) {
        sysAnnouncementService.updateById(announcement);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody SysAnnouncement announcement, HttpServletRequest request) {
        sysAnnouncementService.removeById(announcement.getId());
        return Result.success();
    }
}